package com.jpyl.jpMedicalTreatment.view.activity;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.sdkumeng.share.BHaiGouShareContent;
import com.example.sdkumeng.share.ShareHelper;
import com.forxindu.kit.box.DateKit;
import com.forxindu.kit.box.ViewKit;
import com.jpyl.jpMedicalTreatment.MedicalApplication;
import com.jpyl.jpMedicalTreatment.R;
import com.jpyl.jpMedicalTreatment.common.Constant;
import com.jpyl.jpMedicalTreatment.common.MedicalSettings;
import com.jpyl.jpMedicalTreatment.manager.ActivityManager;
import com.jpyl.jpMedicalTreatment.model.WeiXinPayModel;
import com.jpyl.jpMedicalTreatment.util.LogTools;
import com.jpyl.jpMedicalTreatment.util.MD5Util;
import com.koushikdutta.async.http.BasicNameValuePair;
import com.koushikdutta.async.http.NameValuePair;
import com.sina.weibo.sdk.utils.MD5;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import rx.Observable;

public abstract class BaseActivity extends RxAppCompatActivity {

    protected MedicalApplication app;
    protected MedicalSettings medicalSettings;
    private ActivityManager activityManager;
    private CoordinatorLayout rootlayout;
    private FrameLayout frameLayout;
    protected Toolbar mToolbar;
    protected TextView mTitleTv;
    protected ShareHelper shareHelper;
    protected PopupWindow sharePopupWindow;

    /**
     * 日志输出标志
     **/
    protected final String TAG = this.getClass().getSimpleName();
    /**
     * 日志输出开关
     **/
    protected final boolean IS_SHOW_LOG = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        app = (MedicalApplication) getApplication();
        medicalSettings = new MedicalSettings();
        activityManager = ActivityManager.getInstance(this);
        activityManager.onCreate();
        shareHelper = new ShareHelper(this);
        setContentView(getLayoutId());
        ButterKnife.bind(this);

        /**
         * 在子类使用Observable中的compose操作符，调用，
         * 完成Observable发布的事件和当前的组件绑定，
         * 实现生命周期同步。从而实现当前组件生命周期结束时，自动取消对Observable订阅。
         */
        Observable.interval(1, TimeUnit.SECONDS)
                .compose(this.bindToLifecycle())
                .subscribe();

        afterCreate(savedInstanceState);
    }

    /**
     * 子类需要实现该方法，返回布局文件的id
     *
     * @return layout id
     */
    protected abstract int getLayoutId();

    @Override
    protected void onResume() {
        super.onResume();
        LogTools.v(this, "base onResume");
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityManager.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    /**
     * <b>afterCreate。</b>
     * <p>
     * <b>详细说明：</b>
     * </p>
     * <!-- 在此添加详细说明 --> 绑定控件
     */
    public abstract void afterCreate(Bundle savedInstanceState);


    @Override
    public void setContentView(int layoutResID) {
        rootlayout = (CoordinatorLayout) getLayoutInflater().inflate(R.layout.activity_base, null);
        mToolbar = rootlayout.findViewById(R.id.toolbar);
        mTitleTv = rootlayout.findViewById(R.id.title);

        frameLayout = rootlayout.findViewById(R.id.layout_container);
        // 将传入的layout加载到activity_base的content_frame里面
        getLayoutInflater().inflate(layoutResID, frameLayout, true);
        super.setContentView(rootlayout);
        setUpActionBar();

    }



    /**
     * toolbar的设置
     */
    public void setUpActionBar() {
        setSupportActionBar(mToolbar);
        setTitle("");
        //默认显示返回键
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    /**
     * 当前页面是否显示返回键，默认为显示
     *
     * @param enabled
     */
    public void setDisplayHomeAsUpEnabled(boolean enabled) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(enabled);
    }

    /**
     * 当前页面是否显示toolbar
     *
     * @param enabled
     */
    public void setToolBarEnabled(boolean enabled) {
        if (!enabled) {
            mToolbar.setVisibility(View.GONE);
            mTitleTv.setVisibility(View.GONE);
        } else {
            mToolbar.setVisibility(View.VISIBLE);
            mTitleTv.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 显示日志信息
     */
    public void showLogMsg(String msg) {
        if (IS_SHOW_LOG)
            Log.d(TAG, msg);
    }

    /**
     * [页面跳转]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        startActivity(new Intent(BaseActivity.this, clz));
    }

    /**
     * [携带数据的页面跳转]
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * [含有Bundle通过Class打开编辑界面]
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitleTv.setText(title);
        super.setTitle("");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //微信支付
    public void wechatPay(WeiXinPayModel weiXinPayVo) {
        //首先在调用之前，需要先在代码中进行微信API注册
        IWXAPI wxApi = WXAPIFactory.createWXAPI(this, Constant.APP_ID);
        PayReq request = new PayReq();
        request.appId = weiXinPayVo.getAppid();
        request.partnerId = weiXinPayVo.getMch_id();
        request.prepayId = weiXinPayVo.getPrepay_id();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = weiXinPayVo.getNonce_str();
        request.timeStamp = DateKit.getSecond();
        List <NameValuePair> signParams = new LinkedList<>();
        signParams.add(new BasicNameValuePair("appid", request.appId));
        signParams.add(new BasicNameValuePair("noncestr", request.nonceStr));
        signParams.add(new BasicNameValuePair("package", request.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", request.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", request.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", request.timeStamp));
        request.sign = getAppSign(signParams,Constant.APP_KEY);
        wxApi.sendReq(request);
        Log.e("Activity", "==发起微信支付申请=="+request.sign);
    }

    public String getAppSign(List<NameValuePair> params,String appKey) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            int a = (int)params.get(i).getName().charAt(0);
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            LogTools.e("", params.get(i).getName() + "=" + params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(appKey);

        String appSign = MD5Util.encode(sb.toString()).toUpperCase();
        return appSign;
    }


    //用户分享Window
    public void showShareWindow(BHaiGouShareContent shareContent) {

        View shareLayout = View.inflate(this, R.layout.share_dialog, null);
        LinearLayout shareWeixin = shareLayout.findViewById(R.id.share_weixin_btn);
        LinearLayout shareWeixinFriends = shareLayout.findViewById(R.id.share_weixin_friends_btn);
        LinearLayout shareSina = shareLayout.findViewById(R.id.share_sina_btn);
        LinearLayout outSideLayout =  shareLayout.findViewById(R.id.outside_layout);
        LinearLayout qqZone = shareLayout.findViewById(R.id.share_qq_zone_btn);
        TextView cancelButton =  shareLayout.findViewById(R.id.cancel_btn);
        shareHelper.setShareContent(shareContent);
        outSideLayout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                sharePopupWindow.dismiss();
            }
        });
        shareWeixin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                shareHelper.weixin();
                sharePopupWindow.dismiss();
            }
        });
        shareWeixinFriends.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                shareHelper.weixinFriends();
                sharePopupWindow.dismiss();
            }
        });
        shareSina.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                shareHelper.sinaShare();
                sharePopupWindow.dismiss();
            }
        });
        qqZone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareHelper.qqZoneShare();
                sharePopupWindow.dismiss();
            }
        });
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sharePopupWindow.dismiss();
            }
        });
        sharePopupWindow = new PopupWindow(shareLayout, -1, -2, true);
        sharePopupWindow.setBackgroundDrawable(new BitmapDrawable());
        sharePopupWindow.setAnimationStyle(R.style.popupAnimation);
        sharePopupWindow.showAtLocation(((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0), Gravity.CENTER, 0, 0);
        shareHelper.setUmShareListener(new UMShareListener() {
            @Override
            public void onResult(SHARE_MEDIA share_media) {
                ViewKit.showToast(BaseActivity.this, "分享成功");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {

            }
        });
    }

    public String getVersionName() {
        String localVersion = "";
        try {
            PackageManager manager = getPackageManager();
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            localVersion = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }
}
